import common from "@/common/common.js";
import request from "./request.js";

function wxLogin(callback) {
	//console.log("==========WxLogin ing ======")
	//#ifdef MP-WEIXIN
	wx.getUserProfile({
	  desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
	  success: (userProfile) => {
		// console.log("===========>",userProfile);
		//return false;
		userProfile.from = "wx";
		uniLogin(userProfile, callback);
	  },
	  complete: (res)=> {
		  // console.log("complete", res)
	  }
	})
	//#endif
}

function uniLogin(userProfile, callback) {
	uni.login({
	  // provider: 'weixin', //不用指定，自动获取
	  success: function (loginRes) {
		//console.log(loginRes);
		userProfile.code = loginRes.code;
		// console.log("=======================================================")
		// console.log(userProfile)
		//#ifdef MP-WEIXIN
		// 获取用户信息
		callback(userProfile)
		//#endif
	  }
	});
}

function wxLoginNew(userProfile, callback) {
	console.log(userProfile, "-=-=-=---=-=-=-=-==-=-=")
	if(userProfile) { //新版本获取用户信息
		wxLogin(callback);
	} else {
		uni.login({
			provider: 'weixin',
			success: function (loginRes) {
				//console.log("wxLogin.js", loginRes);
				//return false;
				// 获取用户信息
				uni.getUserInfo({
				  provider: 'weixin',
				  success: function (infoRes) {
					  // console.log(infoRes)
					  infoRes.from = "weixin";
					  infoRes.code = loginRes.code;
					  //callback("wxLogin.js", infoRes);
					  infoRes.from = "wx";
					  callback(infoRes);
					  // uniLogin(infoRes, callback);
				  }
				});
			}
		})
	}
}

function getPhoneForWx(data) {
	return new Promise((resolve, reject)=> {
		request.get("/getPhone", data).then((res) => {
			console.log("=========getPhone===>>", res)
			const phone = res.data.phone;
			resolve(res);
			let customer = common.getCustomer();
			customer.phone = phone;
			common.setCustomer(customer);
		})
	});
}

export default {
	wxLogin: wxLogin,
	wxLoginNew: wxLoginNew,
	getPhoneForWx: getPhoneForWx
}